﻿#region header

#region licence

/*
Copyright (c) 2008, Roger Alsing
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided
that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this list of conditions and the
  following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
  the following disclaimer in the documentation and/or other materials provided with the distribution.

* Neither the name of Roger Alsing nor the names of its contributors may be
  used to endorse or promote products derived from this software without specific prior written
  permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#endregion licence

#region Changelog

//----------   ---   -------------------------------------------------------------------------------
//Purpose:           Math for Generics with help of Linq & Lambda functions.
//Author:            Ir. G.W. van der Vegt
//Url:               http://swiss.codeplex.com
//License:           New BSD License
//copy License:  (c) Roger Alsing , www.rogeralsing.com 2008
//                   Demo code only, lacking exception handling and a few operators
//                   See http://rogeralsing.com/2008/02/27/linq-expressions-calculating-with-generics/
//                   See http://www.puzzleframework.com/Roger/Swiss.cs.txt
//----------   ---   -------------------------------------------------------------------------------
//dd-mm-yyyy - who - description
//----------   ---   -------------------------------------------------------------------------------
//22-01-2010 - veg - Modified version of Web to suite mij needs
//                 - Added One Property that returns a 1 typecast as T.
//                 - Added == and =! operators (and Equals/GetHashCode)
//                 - Added Invert().
//05-02-2010 - veg - Added LT, LTE, GT and GTE.
//----------   ---   -------------------------------------------------------------------------------

#endregion Changelog

#endregion header

namespace Swiss
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Linq.Expressions;
    using System.Reflection;

    // (c) Roger Alsing , www.rogeralsing.com 2008
    // Demo code only, lacking exception handling and a few operators

    /// <summary>
    /// The Magic, Uses Linq and Lambda Functions.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class Number<T>
    {
        private T value;

        private static readonly Func<T, T, T> Add = CompileDelegate(Expression.Add);
        private static readonly Func<T, T, T> Sub = CompileDelegate(Expression.Subtract);
        private static readonly Func<T, T, T> Mul = CompileDelegate(Expression.Multiply);
        private static readonly Func<T, T, T> Div = CompileDelegate(Expression.Divide);
        private static readonly Func<T, T, T> Mod = CompileDelegate(Expression.Modulo);

        //veg:Added
        //private static readonly Func<T, T, T> Eq = CompileDelegate(Expression.Equal);
        private static readonly Func<T, T, Boolean> Lt = CompileBoolDelegate(Expression.LessThan);
        private static readonly Func<T, T, Boolean> Lte = CompileBoolDelegate(Expression.LessThanOrEqual);
        private static readonly Func<T, T, Boolean> Gt = CompileBoolDelegate(Expression.GreaterThan);
        private static readonly Func<T, T, Boolean> Gte = CompileBoolDelegate(Expression.GreaterThanOrEqual);

        /// <summary>
        /// 
        /// </summary>
        /// <param name="operation"></param>
        /// <returns></returns>
        private static Func<T, T, T> CompileDelegate(Func<Expression, Expression, Expression> operation)
        {
            try
            {
                //create two inprameters
                ParameterExpression leftExp = Expression.Parameter(typeof(T), "left");
                ParameterExpression rightExp = Expression.Parameter(typeof(T), "right");

                //create the body from the delegate that we passed in
                Expression body = operation(leftExp, rightExp);

                //create a lambda that takes two args of T and returns T
                LambdaExpression lambda = Expression.Lambda(typeof(Func<T, T, T>), body, leftExp, rightExp);

                //compile the lambda to a delegate that takes two args of T and returns T
                Func<T, T, T> compiled = (Func<T, T, T>)lambda.Compile();
                return compiled;
            }
            catch
            {
                //type T does not support math operations
                return null;
            }
        }

        private static Func<T, T, Boolean> CompileBoolDelegate(Func<Expression, Expression, Expression> operation)
        {
            try
            {
                //create two inprameters
                ParameterExpression leftExp = Expression.Parameter(typeof(T), "left");
                ParameterExpression rightExp = Expression.Parameter(typeof(T), "right");

                //create the body from the delegate that we passed in
                Expression body = operation(leftExp, rightExp);

                //create a lambda that takes two args of T and returns T
                LambdaExpression lambda = Expression.Lambda(typeof(Func<T, T, Boolean>), body, leftExp, rightExp);

                //compile the lambda to a delegate that takes two args of T and returns T
                Func<T, T, Boolean> compiled = (Func<T, T, Boolean>)lambda.Compile();
                return compiled;
            }
            catch
            {
                //type T does not support math operations
                return null;
            }
        }

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="value">Value to store</param>
        private Number(T value)
        {
            this.value = value;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="a"></param>
        /// <returns></returns>
        public static implicit operator Number<T>(T a)
        {
            return new Number<T>(a);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="number"></param>
        /// <returns></returns>
        public static implicit operator T(Number<T> number)
        {
            return number.value;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <returns></returns>
        public static Number<T> operator +(Number<T> a, Number<T> b)
        {
            return new Number<T>(Add(a.value, b.value));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <returns></returns>
        public static Number<T> operator -(Number<T> a, Number<T> b)
        {
            return new Number<T>(Sub(a.value, b.value));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <returns></returns>
        public static Number<T> operator /(Number<T> a, Number<T> b)
        {
            return new Number<T>(Div(a.value, b.value));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <returns></returns>
        public static Number<T> operator *(Number<T> a, Number<T> b)
        {
            return new Number<T>(Mul(a.value, b.value));
        }

        /// <summary>
        /// Modulo
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <returns></returns>
        public static Number<T> operator %(Number<T> a, Number<T> b)
        {
            return new Number<T>(Mod(a.value, b.value));
        }

        /// <summary>
        /// LessThan
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <returns></returns>
        public static Boolean operator <(Number<T> a, Number<T> b)
        {
            return Lt(a.value, b.value);
        }

        /// <summary>
        /// LessThanOrEqual
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <returns></returns>
        public static Boolean operator <=(Number<T> a, Number<T> b)
        {
            return Lte(a.value, b.value);
        }

        /// <summary>
        /// GreaterThan
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <returns></returns>
        public static Boolean operator >(Number<T> a, Number<T> b)
        {
            return Gt(a.value, b.value);
        }

        /// <summary>
        /// GreaterThanOrEqual
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <returns></returns>
        public static Boolean operator >=(Number<T> a, Number<T> b)
        {
            return Gte(a.value, b.value);
        }


        /// <summary>
        /// Calculates 1/a
        /// </summary>
        /// <param name="a">The value to invert</param>
        /// <returns>1/a</returns>
        public static Number<T> Invert(Number<T> a)
        {
            return new Number<T>(Div(One, a.value));
        }

        /// <summary>
        /// See http://msdn.microsoft.com/en-us/library/aa288467(VS.71).aspx
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <returns></returns>
        public static bool operator ==(Number<T> a, Number<T> b)
        {
            return a.value.Equals(b.value);
        }

        /// <summary>
        /// See http://msdn.microsoft.com/en-us/library/aa288467(VS.71).aspx
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <returns></returns>
        public static bool operator !=(Number<T> a, Number<T> b)
        {
            return !(a.value.Equals(b.value));
        }

        /// <summary>
        /// Override the Object.Equals(object o) method:
        /// 
        /// See http://msdn.microsoft.com/en-us/library/aa288467(VS.71).aspx
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        public override bool Equals(object o)
        {
            try
            {
                return (bool)((Object)value == (Object)o);
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// Override the Object.GetHashCode() method: 
        /// 
        /// See http://msdn.microsoft.com/en-us/library/aa288467(VS.71).aspx
        /// </summary>
        /// <returns></returns>
        public override int GetHashCode()
        {
            return value.GetHashCode();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="a"></param>
        /// <returns></returns>
        public static bool IsDefault(Number<T> a)
        {
            return a == (Number<T>)default(T);
        }

        /// <summary>
        /// Tests if Type T can be used. 
        /// </summary>
        public static bool IsNumeric
        {
            get
            {
                //ugly hack..
                //requires an exception in the delegate generator 
                //in order to determine if the type supports math operations
                if (Add == null)
                    return false;
                else
                    return true;
            }
        }

        /// <summary>
        /// Hack to get a value of 1 into a Generic so we can use invert.
        /// 
        /// Due to the implementation (it sets the value ones when 
        /// requested) the code should perform well.
        /// </summary>
        public static T One
        {
            get
            {
                if (fOne.Equals(default(T)))
                {
                    PropertyInfo pi = typeof(Number<T>).GetProperty("One", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
                    if (pi != null)
                    {
                        pi.SetValue(null, 1, null);
                    }
                }
                return fOne;
            }
            set
            {
                fOne = value;
            }
        }
        private static T fOne = default(T);
    }

    /// <summary>
    /// A Class for comparing values of T with Min/Max values.
    /// </summary>
    /// <typeparam name="T">The type to compare</typeparam>
    public struct MinMax<T>
    {
        /// <summary>
        /// Create a new MinMax Object
        /// </summary>
        /// <param name="Min">The Minimum for Comparisments</param>
        /// <param name="Max">The Maximum for Comparisments</param>
        public MinMax(T Min, T Max)
        {
            this.Min = Min;
            this.Max = Max;
        }

        /// <summary>
        /// The Minimum for Comparisments
        /// </summary>
        public T Min;

        /// <summary>
        /// The Maximum for Comparisments
        /// </summary>
        public T Max;

        /// <summary>
        /// Returns true if the Min&lt;=value&lt;=Max
        /// </summary>
        /// <param name="value">The value to test</param>
        /// <returns>true if the Min&lt;=value&lt;=Max</returns>
        public Boolean InRange(T value)
        {
            Boolean Result = ((Number<T>)Min <= (Number<T>)value);
            if (Result)
            {
                Result = (Number<T>)value <= (Number<T>)Max;
            }

            return Result;
        }

        /// <summary>
        /// Returns true if the Min&lt;value&lt;Max
        /// </summary>
        /// <param name="value">The value to test</param>
        /// <returns>true if the Min&lt;value&lt;Max</returns>
        public Boolean InBewteen(T value)
        {
            Boolean Result = ((Number<T>)Min < (Number<T>)value);
            if (Result)
            {
                Result = (Number<T>)value < (Number<T>)Max;
            }

            return Result;
        }
    }
}